package com.hkpw.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.hikvision.artemis.sdk.config.ArtemisConfig;
import com.hkpw.common.core.domain.entity.SysDictData;
import com.hkpw.common.exception.GlobalException;
import com.hkpw.hik.ArtemisApiPathEnum;
import com.hkpw.system.config.HkConfig;
import com.hkpw.system.constants.HKDictType;
import com.hkpw.system.constants.HkCollegeSafeApi;
import com.hkpw.system.domain.EventSubscribe;
import com.hkpw.system.domain.HkResult;
import com.hkpw.system.domain.request.HkDoorEventSubscribeRequest;
import com.hkpw.system.domain.request.HkDoorEventUnSubscribeRequest;
import com.hkpw.system.domain.vo.DoorEventResult;
import com.hkpw.system.domain.vo.EventSubscribeViewVo;
import com.hkpw.system.domain.vo.EventsSubscribeViewResultVo;
import com.hkpw.system.mapper.EventSubscribeMapper;
import com.hkpw.system.service.IEventSubscribeService;
import com.hkpw.system.service.ISysDictTypeService;
import com.hkpw.system.utils.HkFaceApiUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 事件订阅Service业务层处理
 *
 * @author andy
 * @date 2022-09-29
 */
@Slf4j
@Service
public class EventSubscribeServiceImpl extends BaseServiceImpl implements IEventSubscribeService {

    @Autowired
    private EventSubscribeMapper eventSubscribeMapper;

    @Autowired
    private HkConfig hkConfig;


    /**
     * 字典service，用于查询订阅的事件列表
     */
    @Autowired
    private ISysDictTypeService sysDictTypeService;


    /**
     * 订阅门禁事件
     * String typestr="[197390,197391,198148,198150,198400,198401,198402,198404,198405,198657,198913,198916,198919,198922,199172,199169,199171,199941,199942,200453,200454,200455,200456,199708,199709,199710,199711,199712,199713,199714,199715,196885,196887,198914,198915,197121,197122,197123,197124,197125,197634,197633,198145,197635,196886,196897,197127,197128,197136,197137,197140,197158,196888,197141,197142,196889,197143,197144,196890,197145,197146,196891,197147,197148,196892,197149,197150,196893,197151,197160,197161,197162,197163,196874,196875,196883,196884,198918,198921,199425,197383,197392,197393,197394,197395,197396,197397,197400,197401,198146,198149,197399,198658,197889,197384,197378,197377,197138,197134,199429,199681,199428]";
     *
     * @return
     */
    @SneakyThrows
    @Override
    public String subscribeDoorEvent() {
//        Map<String, String> path = new HashMap<String, String>();
//        path.put("https://", HkCollegeSafeApi.DOOR_EVENT_SUBSCRIBE_URL);
        //查询订阅事件列表
        List<SysDictData> typeList = sysDictTypeService.selectDictDataByType(HKDictType.EVENT_TYPE.getValue());
        if (CollUtil.isEmpty(typeList)) {
            throw new RuntimeException("未查询到订阅类型");
        }
        List<Long> types = typeList.stream().map(type -> Long.valueOf(type.getDictValue())).collect(Collectors.toList());
        //首先取消所有订阅
        unSubscribeByEventTypes(types);
        HkDoorEventSubscribeRequest hkDoorEventSubscribeRequest = new HkDoorEventSubscribeRequest();
        hkDoorEventSubscribeRequest.setEventTypes(types);
        hkDoorEventSubscribeRequest.setEventDest(hkConfig.getEventDest() + HkCollegeSafeApi.ZHGY_DOOR_EVENT_NOTIFY);

        JSONObject result = callPostApiCommonFun(HkCollegeSafeApi.DOOR_EVENT_SUBSCRIBE_URL, hkDoorEventSubscribeRequest);
        DoorEventResult doorEventResult = JSONObject.parseObject(result.toJSONString(), DoorEventResult.class);
        log.info(doorEventResult.toString());
        return result.toJSONString();
    }

    /**
     * 查询事件订阅
     *
     * @param eventType 事件订阅主键
     * @return 事件订阅
     */
    @Override
    public EventSubscribe selectEventSubscribeByEventType(Long eventType) {
        return eventSubscribeMapper.selectEventSubscribeByEventType(eventType);
    }

    /**
     * 查询事件订阅列表
     *
     * @return 事件订阅
     */
    @SneakyThrows
    @Override
    public List<EventSubscribeViewVo> selectEventSubscribeList() {
        //查询订阅事件的URL
        Map<String, String> path = HkFaceApiUtils.getHkUrlPath(HkCollegeSafeApi.DOOR_EVENT_SUBSCRIBE_VIEW_URL);
        ArtemisConfig artemisConfig = new ArtemisConfig(hkConfig.getHost(), hkConfig.getAppKey(), hkConfig.getAppSecret());
        JSONObject result = callPostApiCommonFun(HkCollegeSafeApi.DOOR_EVENT_SUBSCRIBE_VIEW_URL, null);
//        String result = ArtemisHttpUtil.doPostStringArtemis(artemisConfig, path, null, null, null, "application/json");
        log.info("EventSubscribeServiceImpl.selectEventSubscribeList():result={}", result);
        String code = result.getString(ArtemisApiPathEnum.KEY_CODE.value());
        if (!ArtemisApiPathEnum.CODE_SUCCESS.value().equals(code)) {
            throw new GlobalException(result.toJSONString());
        }
        HkResult<JSONObject> r = JSONObject.parseObject(result.toJSONString(), HkResult.class);
        if (ObjectUtil.isNotNull(r) && r.getCode().equals(ArtemisApiPathEnum.CODE_SUCCESS.value())) {
            List<EventSubscribeViewVo> eventSubscribeViewVoList = new ArrayList<>();
            JSONObject data = r.getData();
            JSONArray detail = data.getJSONArray("detail");
            if (ObjectUtil.isNotNull(detail)) {
                List<EventsSubscribeViewResultVo> resultVos = detail.toJavaList(EventsSubscribeViewResultVo.class);
                resultVos.forEach(eventsSubscribeViewResultVo -> {
                    List<Long> eventTypes = eventsSubscribeViewResultVo.getEventTypes();
                    eventTypes.forEach(event -> {
                        EventSubscribeViewVo eventSubscribeViewVo = new EventSubscribeViewVo();
                        eventSubscribeViewVo.setEventType(event);
                        eventSubscribeViewVo.setEventDest(eventsSubscribeViewResultVo.getEventDest());
                        eventSubscribeViewVoList.add(eventSubscribeViewVo);
                    });
                });
            }
            return eventSubscribeViewVoList;
        } else {
            throw new RuntimeException(r.getMsg());
        }
    }

    /**
     * 新增事件订阅
     *
     * @param eventSubscribe 事件订阅
     * @return 结果
     */
    @Override
    public int insertEventSubscribe(EventSubscribe eventSubscribe) {
        return eventSubscribeMapper.insertEventSubscribe(eventSubscribe);
    }

    /**
     * 修改事件订阅
     *
     * @param eventSubscribe 事件订阅
     * @return 结果
     */
    @Override
    public int updateEventSubscribe(EventSubscribe eventSubscribe) {
        return eventSubscribeMapper.updateEventSubscribe(eventSubscribe);
    }

    /**
     * 批量删除事件订阅
     *
     * @param events 需要删除的事件订阅主键
     * @return 结果
     */
    @SneakyThrows
    @Override
    public int unSubscribeByEventTypes(List<Long> events) {
        log.info("unSubscribeByEventTypes.length={}", events.size());
        HkDoorEventUnSubscribeRequest unSubscribeRequest=new HkDoorEventUnSubscribeRequest();
        unSubscribeRequest.setEventTypes(events);

        JSONObject result = callPostApiCommonFun(HkCollegeSafeApi.DOOR_EVENT_UNSUBSCRIBE_URL, unSubscribeRequest);
        log.info("EventSubscribeServiceImpl.selectEventSubscribeList():result={}", result);
        String code = result.getString(ArtemisApiPathEnum.KEY_CODE.value());
        if (ArtemisApiPathEnum.CODE_SUCCESS.value().equals(code)) {
            return events.size();
        } else {
            throw new RuntimeException(result.toJSONString());
        }

    }

    /**
     * 删除事件订阅信息
     *
     * @param eventType 事件订阅主键
     * @return 结果
     */
    @Override
    public int deleteEventSubscribeByEventType(Long eventType) {
        return eventSubscribeMapper.deleteEventSubscribeByEventType(eventType);
    }
}
